<template>
	<view class="box">
		<view class="step-item" v-for="(step,index) in info" :key="index">
			<view class="title">步骤{{ index + 1 }}</view>
			<view class="video" @click="play(index)">
				<video
					:src="step.video"
					loop
					:id="`video-${index}`"
					:controls="false"
					:show-center-play-btn="false"
				></video>
				<view v-show="index !== playingIndex" class="play-btn">
					<u-icon name="play-circle-fill" size="80"></u-icon>
				</view>
			</view>
			<view class="text">{{ step.text }}</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'steps',
		props: {
			info: {
				type: Array,
				default: () => ([])
			}
		},
		data() {
			return {
				// 控制视频播放暂停
				videoContextList: [],
				// 当前正在播放的视频(-1表示没有正在播放的视频)
				playingIndex: -1
			}
		},
		watch: {
			info() {
				this.init()
			}
		},
		methods: {
			// 初始化
			init() {
				const that = this
				this.videoContextList = this.info.map((item,index) => {
					const observer = uni.createIntersectionObserver(that);
					observer.relativeToViewport().observe(`#video-${index}`, (res) => {
						if (res.intersectionRatio <= 0 && that.playingIndex === index) {
						  // 视频滚出可视区域，暂停视频
						  console.log('停止'+`#video-${index}`);
						  that.videoContextList[index].seek(0)
						  that.videoContextList[index].pause()
						  that.playingIndex = -1
						}
					});
					return uni.createVideoContext(`video-${index}`, that)
				})
			},
			play(index) {
				if(this.playingIndex !== -1) {
					this.videoContextList[this.playingIndex].seek(0)
					this.videoContextList[this.playingIndex].pause()
				}
				this.videoContextList[index].play()
				this.playingIndex = index
			}
		}
	}
</script>
<style lang="scss" scoped>
	.step-item + .step-item {
		margin-top: 30rpx;
	}
	.title {
		font-size: 40rpx;
		font-weight: 700;
	}
	.video {
		margin: 30rpx 0;
		width: 100%;
		padding-top: 100%;
		position: relative;
		border-radius: 40rpx;
		overflow: hidden;
		video {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
		}
		.play-btn {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%,-50%);
		}
	}
</style>